package cn.jolyoulu.common.web.interceptors;

import cn.jolyoulu.common.core.constant.GlobalConstant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.UUID;

/**
 * @Author: JolyouLu
 * @Date: 2022/1/21 10:46
 * @Version 1.0
 */
@Slf4j
@Component
public class PreInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //添加调用链条
        String traceId = request.getHeader(GlobalConstant.TRACE_ID);
        //没有TRACE_ID请求头，创建一个
        if (StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(GlobalConstant.TRACE_ID, traceId);
        return true;
    }
}
